import React, { useEffect, useLayoutEffect, useMemo, useState } from "react"

// import { registerMicroApps} from 'qiankun';

export const MicroAppContext = React.createContext<MicroAppContextProps>({} as MicroAppContextProps);

interface RouteItemQiankun {
  container?: string
  activeRule?: any
  name?: any
}
interface RouteItemBase {
  path: string
  entry: string
  title?: string | ((routeItem: RouteItemBase) => string)
}
type RouteItem = RouteItemBase & RouteItemQiankun

interface MicroAppProviderProps {
  basename?: string
  children?: React.ReactNode,
  defaultPage?: string
  modules?: any[],
  publicPath?: string
  spin?: React.ReactNode
  routes: any[]
  name: string
  notFound?: React.ReactNode
  env?: string
  ErrorBoundary?: React.ReactNode
}
interface MicroAppContextProps extends MicroAppProviderProps {
  routeMap: any
moduleMap: any
}
const createRouteMap = (routes) => {
  let routeMap = {}, moduleMap = {};

  const flatten = (_routes: any) => {
    _routes.forEach((item) => {
      if (Array.isArray(item.children) && item.children.length > 0) {

        flatten(item.children);
      } else {
        if (item.path) {
          routeMap[item.path] = { ...item };
        } else {
          moduleMap[item.activeModule] = { ...item };
        }
      }
    });
  };
  flatten(routes);

  return { routeMap ,moduleMap}
}

export const MicroAppProvider = ({ modules = [], spin, ErrorBoundary, publicPath, name, defaultPage = '/', notFound, basename = '', routes, children }: MicroAppProviderProps) => {
  const [routeMap, setRouteMap] = useState({});
  const [moduleMap, setModuleMap] = useState({});

  useEffect(() => {

    (window as any).__micro_app = {
      name,
      routes
    };

  }, [])
  useEffect(() => {
    // modules.forEach(module => {
    //   module.onRoutesChange && module.onRoutesChange(routes)
    // })
    const {moduleMap:_moduleMap,routeMap:_routeMap} = createRouteMap(routes);
    setRouteMap({ ..._routeMap })
    setModuleMap({ ..._moduleMap })
  }, [routes])
  const value = useMemo(() => {

    return {
      routes,
      basename,
      name,
      publicPath,
      defaultPage,
      modules,
      routeMap,
      moduleMap,
      spin,
      ErrorBoundary,
      notFound
    }
  }, [routeMap,moduleMap])
  return <MicroAppContext.Provider value={value}>
    {children}
  </MicroAppContext.Provider>
}